<?php
//ob_start();
set_time_limit(120);
header('Content-type: text/html;charset=utf-8');
require_once('./Snoopy/Snoopy.class.php');
$Snoop = new Snoopy();
//选择出所有的已经订阅的rss
$lasttime = time()-3600;
$uid = intval($_GET['uid'])?intval($_GET['uid']):0;  //要采集的用户的uid

$filepath = "blogrss$uid.rss";
$rs['listurl'] = 'http://feeds.qzone.qq.com/cgi-bin/cgi_rss_out?uin=474336208';
if (file_exists($filepath) && filemtime($filepath) + 1800 > time()) { //判断此文件是否为半小时更新的,如果超过半小时,更新文件
    $contents = file_get_contents($filepath);
    $rss  = simplexml_load_string ($contents,'SimpleXMLElement',LIBXML_NOCDATA);
}else{
  $rss_url = $rs['listurl'];
  $contents = file_get_contents($rss_url);
  preg_match('#encoding="([^\"]*)"?#',$contents,$matches);
  if( 'UTF-8' != $matches[1] ){
   $contents = preg_replace('#encoding="([^\"]*)"?#','encoding="UTF-8"',$contents);
   $contents = mb_convert_encoding ($contents,'UTF-8',$matches[1]);
  }
  file_put_contents($filepath, $contents);  //缓存列表页到.txt中
  $rss     =  simplexml_load_string($contents,'SimpleXMLElement',LIBXML_NOCDATA);
}
var_dump(count($rss->channel->item));
if(is_null($_GET['itemid'])) {
	$itemid = count($rss->channel->item)-1;
}else{
    $itemid = intval($_GET['itemid']);  //第几篇文章
}
var_dump($itemid);
var_dump(empty($rss->channel->item[$itemid]));
if(empty($rss->channel->item[$itemid]) || $itemid<0){
	die('采集完成');
}
$message = (array)$rss->channel->item[$itemid];
echo '开始采集-'.$title.'-的内容<br>';


/*博客内容*/
$blog = array();
$blog['subject']     = ((string)$rss->channel->item[$itemid]->title);
$blog['uid']       = $uid;
$blog['username']  = $username;
$blog['dateline']  = strtotime((string)$rss->channel->item[$itemid]->pubDate);
$blog['message']   = trim((string)$rss->channel->item[$itemid]->description);
var_dump($blog['message']);

/*---------插入文章内容----------------*/

  //先保存文章中的图片到本地
  $imgarr = $Snoop->_stripimgs($blog['message']);
  var_dump($imgarr);
  if (is_array($imgarr)) {
    foreach ($imgarr as $img) {
         echo '保存图片到本地'.'<br>'; 
         $localimg = copy2local($img);//保存图片到本地
		 $blog['message'] = str_replace($img,$localimg,$blog['message']);//替换图片地址
    }
  }
  $blog['message'] = ($blog['message']);


echo '成功采集一篇文章'.'-'.$blog['subject'].'-<br>';
/*-----------------------------------*/

/**
*保存远程文件到本地
*/
function copy2local($url){
    $localpath = './attachment/'.rand(100000,999999).'.jpg';
	file_put_contents($localpath, file_get_contents($url));
	return $localpath;
}

$itemid--;
$get_arr = 'uid='.$blog['uid'].'&itemid='.$itemid;
//flush();
echo 'ok';
?>
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!--
   //alert('<?php echo $get_arr ?>');
	window.location.href='?<?php echo $get_arr ?>';
//-->
</SCRIPT>